﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Swd05.SH.Bll;
using Swd05.SH.Interfaces;

namespace Swd05.SH.Dal
{
	class RamScriptFactory : IScriptFactory
	{
		private Dictionary<string, string> list = new Dictionary<string,string>();
		
		#region Properties
		private Dictionary<string, string> List
		{
			get
			{
				return this.list;
			}
		}
		#endregion
		#region Methods
		public IScriptEngine Create(object context )
		{
			ScriptEngine se = null;

			se = new ScriptEngine(context, this.FindById(context.GetType().FullName));

			return se;
		}
		public void Connect(string connectionstring)
		{
			// pure virtual
		}
		public void Commit(string id, string stream)
		{
			if( this.List.ContainsKey( id ) )
			{
				if( stream.Length == 0 )
				{
					this.List.Remove( id );
				}
				else
				{
					this.List[ id ] = stream;
				}
			}
			else
			{
				this.List.Add( id, stream );
			}
		}
		public bool Exists(string id)
		{
			return this.List.ContainsKey( id );
		}
		public string FindById(string id)
		{
			string script = string.Empty;
			
			if( this.Exists( id ) )
			{
				script = this.List[ id ];
			}
			else
			{
				this.List.Add( id, script );	// AutoAppend
			}
			return script;
		}
		public System.Data.DataTable Load()
		{
			DataSet ds = null;
			DataTable dt = null;

			ds = new DataSet("ds.scripts");

			dt = ds.Tables.Add("scripts");
			dt.Columns.Add("Id", typeof(string));
			dt.Columns.Add("Script", typeof(string));
			dt.Columns.Add("Datum", typeof(DateTime));

			foreach ( KeyValuePair<string, string> kvp in this.List )
			{
				dt.Rows.Add(new object[3] { kvp.Key, kvp.Value, DateTime.Now });
			}
			dt.AcceptChanges();

			return dt;
		}
		#endregion
		#region Properties
		#endregion
	}
}
